package com.songcha.module_bookreader.ui.activity.reader

import com.google.gson.Gson
import com.songcha.module_bookreader.api.BookReaderApiManager
import com.songcha.module_bookreader.bean.book.BookChapterContentDataBean
import com.songcha.module_bookreader.utils.BookUtil
import com.songcha.module_bookreader.utils.FileUtils
import com.songcha.library_business.bean.book.BookChapterCatalogBean
import com.songcha.library_business.mvvm.BusinessRepository
import com.songcha.library_business.util.BookFileUtil
import com.songcha.library_network.bean.BaseIntDataBean
import io.reactivex.Observable
import java.io.FileNotFoundException

class BookReadRepository:BusinessRepository() {
    fun getChapterContent(chapterId:Int):Observable<BookChapterContentDataBean>{
        return BookReaderApiManager.api.getBookChapterContent(chapterId)
    }

    fun getDiskChapterCotent(bookId:String,chapter:Int):Observable<BookChapterContentDataBean>{
        return Observable.create{
            if(!BookUtil.isBookChapterFileExist(bookId,chapter)){
                it.onComplete()
            }else{
                val bean=BookChapterContentDataBean.BookChapterContentBean(0,0,"")
                val dataBean=BookChapterContentDataBean(bean)
                it.onNext(dataBean)
            }
        }
    }

    //从下载书籍中获取章节信息
    fun getBookChapterCatalogFromDownload(bookId:String): Observable<BookChapterCatalogBean>{
        return Observable.create{
            try{
                val str=FileUtils.getFileOutputString(BookFileUtil.getBookFilePath(bookId)+"chapter.json","utf-8")
                val bean=Gson().fromJson(str.trim(),BookChapterCatalogBean::class.java)
                it.onNext(bean)
                it.onComplete()
            }catch (e:Exception){
                e.printStackTrace()
                it.onError(FileNotFoundException())
            }
        }
    }

    fun completeTask(taskId:Int):Observable<BaseIntDataBean>{
        return BookReaderApiManager.api.completeTask(taskId)
    }

}